#!/usr/bin/env node

import { program } from 'commander'
import { arch, platform } from 'os'
import { version } from '../package.json'
import { Arch, Message, Myapp, Name, Nametype, Userwin } from './interface'
import Serve from './serve'
import { findSoftware, Runarduino } from './run'
import { Socket } from 'socket.io'
import Openfile from './open'
program.version(version);
const myapp: Myapp = {
    name: '配置中心',
}
program.command('list').description('查看可以修复的列表').action(function (_e, arg) {
    console.log('555')
    console.log(arg)
})

const port = process.env.PORT || 1212;

program.command('serve')
    .description('启动服务器')
    .action(function (_e) {
        servefunc(myapp)
    })


const userwin: Userwin = {
    version,
    arch: arch() as Arch,
    type: platform()
}

export function servefunc(myapp: Myapp) {
    const serve = new Serve(port)
    serve.io.on('connection', (s: Socket) => {
        s.on('message', (type: Message, message: string) => {
            switch (type) {
                case 'A0':
                    s.emit('A0', myapp)
                    break
                case 'A1':
                    s.emit('A1', userwin)
                    break;
                case 'A2':
                    s.emit('A2', A2list(['arduino', 'arduinodrivers', 'leap', 'cpp']))
                    break;
                default:
                    defaultevent(type, message)
            }
        })
    })
}

/**
 * A2 软件需要环境检查
 * @param name 
 */
function A2list(name: Name[]): Nametype[] {
    return name.map(v => {
        return {
            name: v,
            type: findSoftware(v)
        }
    })
}


interface Ioption {
    userwin: Userwin,

}



export default class Installpackage {
    option: Ioption
    constructor(option: Ioption) {
        this.option = option
    }
}


// export  async function Installpackage(option: Options) {
//     const { type, name } = option
//     if (type === 'command') {
//         console.log('start')
//         for (let v of name) {
//             if (v === 'arduino') {
//                 const d = await Runarduino()
//                 console.log(d)
//             }
//         }
//     }
// }

async function run(name: Name) {
    if (name === 'arduino') {
        const d = await Runarduino()
        console.log(d)
    }
}


function defaultevent(event: Message, message: string) {
    const da = JSON.parse(message)
    switch (event) {
        case 'open':
            Openfile(da.name)
            break;
        case 'del':
            console.log('del')
            break;
        case 'run':
            run(da.name)
            break;
        case 'test':
            run(da.name)
            break
        default:
            console.log(666)
    }

}














program.parse(process.argv);